package com.quanyan.place.service.impl;

import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.*;
import com.quanyan.place.entity.apiresp.RespSupplierVo;
import com.quanyan.place.mapper.TbBizPlaceMapper;
import com.quanyan.place.mapper.TbCityMapper;
import com.quanyan.place.mapper.TbSupplierMapper;
import com.quanyan.place.mapper.TbSupplierUserMapper;
import com.quanyan.place.request.SupplierSearchRequest;
import com.quanyan.place.service.SupplierService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by yangyun on 2016/4/14.
 */
@Service("supplierService")
public class SupplierServiceImpl implements SupplierService {

    @Autowired
    private TbSupplierMapper supplierMapper;

    @Autowired
    private TbSupplierUserMapper tbSupplierUserMapper;

    @Autowired
    private TbBizPlaceMapper tbBizPlaceMapper;

    @Autowired
    TbCityMapper tbCityMapper;

    /**
     * 增加（编辑）供应商
     * @param supplier
     * @return
     */
    @Override
    public APIResponse addSupplier(Supplier supplier) {
        if (supplier.getId() == null){
            TbSupplier tbSupplier = new TbSupplier();
            tbSupplier.setName(supplier.getName());
            tbSupplier.setContact(supplier.getContact());
            tbSupplier.setPhone(supplier.getPhone());
            tbSupplier.setAddress(supplier.getAddress());
            tbSupplier.setBcId(supplier.getBcId());
            tbSupplier.setBcBank(supplier.getBcBank());
            tbSupplier.setBcCardno(supplier.getBcCardno());
            tbSupplier.setBcAccountName(supplier.getBcAccountName());
            tbSupplier.setBcName(supplier.getBcAccountName());
            tbSupplier.setCityId(supplier.getCityId());
            tbSupplier.setProvinceId(supplier.getProvinceId());
            tbSupplier.setIsChain(supplier.getIsChain());
            //如果不是小商品的供应商录入，则要存入税率
            if (!"1".equals(supplier.getSupplierType().toString())){
                tbSupplier.setBcTaxiRate(BigDecimal.ONE); // 税率
            }
            tbSupplier.setFax(supplier.getFax());
            tbSupplier.setComment(supplier.getComment());
            tbSupplier.setPriority((short) Constants.ZERO);
            tbSupplier.setCreateTime(Calendar.getInstance().getTime());
            tbSupplier.setUpdateTime(Calendar.getInstance().getTime());
            tbSupplier.setIsDelete(Constants.IS_DELETE_FALSE);
            tbSupplier.setSupplierType(supplier.getSupplierType());
            this.supplierMapper.insert(tbSupplier);
        } else {
            TbSupplier dbSupplier = supplierMapper.selectByPrimaryKey(supplier.getId());
            dbSupplier.setName(supplier.getName());
            dbSupplier.setAddress(supplier.getAddress());
            dbSupplier.setCityId(supplier.getCityId());
            dbSupplier.setProvinceId(supplier.getProvinceId());
            dbSupplier.setIsChain(supplier.getIsChain());
            dbSupplier.setBcId(supplier.getBcId());
            dbSupplier.setBcBank(supplier.getBcBank());
            dbSupplier.setBcCardno(supplier.getBcCardno());
            dbSupplier.setBcAccountName(supplier.getBcAccountName());
            dbSupplier.setBcName(supplier.getBcAccountName());
            dbSupplier.setPhone(supplier.getPhone());
            dbSupplier.setFax(supplier.getFax());
            dbSupplier.setContact(supplier.getContact());
            dbSupplier.setComment(supplier.getComment());
            dbSupplier.setUpdateTime(Calendar.getInstance().getTime());
            dbSupplier.setSupplierType(supplier.getSupplierType());
            supplierMapper.updateByPrimaryKey(dbSupplier);
        }
        return APIResponse.returnSuccess();
    }

    public APIResponse<?> getSupplierById(Integer id) {
        if (id != null){
            TbSupplier supplier = supplierMapper.selectByPrimaryKey(id);
            return  APIResponse.returnSuccess(supplier);
        }
        return null;
    }

    /**
     * 查询供应商
     * @return
     */
    public PageObj<List<RespSupplierVo>> supplierSearch(SupplierSearchRequest searchBean) {
        TbSupplierExample example=new TbSupplierExample();
        Integer pageNum = 0;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        Map<Integer,String> cityMap=new HashMap<>();
        List<RespSupplierVo> listVo=new ArrayList<>();
        String type="1";
        TbSupplierExample.Criteria criterial = example.createCriteria();
        TbSupplierExample.Criteria criteriaOr = example.createCriteria();
        List<TbCity> cityList=this.getCityInfo(1);
        if (cityList!=null){
            for (TbCity city:cityList){
                cityMap.put(city.getId(),city.getName());
            }
        }
        if (searchBean != null){

            pageNum = searchBean.getPageNum();
            pageSize = searchBean.getPageSize();
            if (StringUtils.isNotEmpty(searchBean.getKey())){
                criterial.andNameLike("%" + searchBean.getKey().trim() + "%");
            }
            if (searchBean.getCityId() != null){
                criterial.andCityIdEqualTo(searchBean.getCityId());
            }
            if (searchBean.getSupplierType()!=null){
                criterial.andSupplierTypeEqualTo(searchBean.getSupplierType());
            }
            if (searchBean.getPlaceSupplierType()!=null){
                criterial.andSupplierTypeEqualTo(searchBean.getPlaceSupplierType());
            }

            if (StringUtils.isNotEmpty(searchBean.getKey())){
                try{
                    criteriaOr.andIdEqualTo(Integer.parseInt(searchBean.getKey()));
                }catch (Exception e){
                    criteriaOr.andIdEqualTo(9999999);
                }
            }
            if (searchBean.getCityId() != null){
                criteriaOr.andCityIdEqualTo(searchBean.getCityId());
            }
            if (searchBean.getSupplierType()!=null){
                criteriaOr.andSupplierTypeEqualTo(searchBean.getSupplierType());
            }
            if (searchBean.getPlaceSupplierType()!=null){
                criteriaOr.andSupplierTypeEqualTo(searchBean.getPlaceSupplierType());
            }
        }
        criterial.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        criteriaOr.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        int total =supplierMapper.countByExample(example);
        example.or(criteriaOr);
        example.setOrderByClause("id desc");
        example.setPage(new Page(pageNum * pageSize, pageSize,total));
        List<TbSupplier> records = supplierMapper.selectByExample(example);
        for (TbSupplier vo:records){
            RespSupplierVo resp=new RespSupplierVo();
            resp.setCityName(cityMap.get(vo.getCityId()));
            resp.setId(vo.getId());
            resp.setCityId(vo.getCityId());
            resp.setPhone(vo.getPhone());
            resp.setName(vo.getName());
            resp.setAddress(vo.getAddress());
            resp.setBcAccountName(vo.getBcAccountName());
            resp.setBcBank(vo.getBcBank());
            resp.setBcEmail(vo.getBcEmail());
            resp.setBcId(vo.getBcId());
            resp.setBcCardno(vo.getBcCardno());
            resp.setBcInvoice(vo.getBcInvoice());
            resp.setBcName(vo.getBcName());
            resp.setBcTaxiRate(vo.getBcTaxiRate());
            resp.setComment(vo.getComment());
            resp.setContact(vo.getContact());
            resp.setProvinceId(vo.getProvinceId());
            resp.setPriority(vo.getPriority());
            resp.setFax(vo.getFax());
            resp.setIsChain(vo.getIsChain());
            resp.setIsDelete(vo.getIsDelete());
            resp.setCreateTime(vo.getCreateTime());
            resp.setUpdateTime(vo.getUpdateTime());
            listVo.add(resp);
        }

        PageObj<List<RespSupplierVo>> result = PageObj.create(total, pageNum, pageSize, listVo);
        return result;
    }


    public List<TbCity> getCityInfo(Integer isEnable){
        TbCityExample tbCityExample = new TbCityExample();
        TbCityExample.Criteria tbCityCriteria = tbCityExample.createCriteria();
        tbCityCriteria.andIsEnableEqualTo(isEnable);
        List<TbCity> list = tbCityMapper.selectNameByExample(tbCityExample);
        return  list;
    }


    @Override
    public APIResponse<?> deleteSupplier(Integer supplierId) {
        TbSupplier supplier = supplierMapper.selectByPrimaryKey(supplierId);
        supplier.setIsDelete(Constants.IS_DELETE_TRUE); // 标记为已删除
        supplierMapper.updateByPrimaryKeySelective(supplier);
        return APIResponse.returnSuccess();
    }



    /**
     * 通过关键字搜索供应商
     * @param keywords
     * @param city
     * @return
     */
    public List<TbSupplier> querySupplierByKeywordsAndAddress(String keywords, Integer city) {
        TbSupplierExample example=new TbSupplierExample();
        TbSupplierExample.Criteria criterial = example.createCriteria();
        if(city != null){
            criterial.andCityIdEqualTo(city);
        }
        if(StringUtils.isNotEmpty(keywords)){
            criterial.andNameLike("%"+keywords+"%");
            TbSupplierExample.Criteria subCriteria = example.createCriteria();
            subCriteria.andAddressLike("%" + keywords + "%");
            example.or(subCriteria);
        }
        List<TbSupplier> result = supplierMapper.selectByExample(example);
        return result;
    }

    /**
     * 供应商关联用户（支持多个用户）
     * @param supplierId
     * @param adminUserIds
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> supplierRelateAdminUsers(Integer supplierId, List<Integer> adminUserIds) {
        if (null == supplierId){
            return APIResponse.returnFail("请选择供应商！");
        }
        if (null == adminUserIds || adminUserIds.size() == 0){
            return APIResponse.returnFail("至少选择一个用户！");
        }
        APIResponse response = this.getSupplierById(supplierId);
        if (null == response.getData()){
            return APIResponse.returnFail("该供应商不存在！");
        }
        TbSupplier tbSupplier = (TbSupplier)response.getData();
        for (Integer adminUserId : adminUserIds){
            TbSupplierUser tbSupplierUser = new TbSupplierUser();
            tbSupplierUser.setSupplierId(tbSupplier.getId());
            tbSupplierUser.setAdminUserId(adminUserId);
            tbSupplierUser.setIsDelete(PlaceConstants.NO);
            try{
                tbSupplierUserMapper.insertSelective(tbSupplierUser);
            }catch (Exception e){
                throw e;
            }
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 根据adminUserId查询供应商
     * @param adminUserId
     * @return
     */
    @Override
    public APIResponse<List<TbSupplier>> getSupplierListByAdminUid(Integer adminUserId) {
        if (null == adminUserId){
            return APIResponse.returnFail("adminUserId为空！");
        }
        TbSupplierUserExample tbSupplierUserExample = new TbSupplierUserExample();
        tbSupplierUserExample.createCriteria().andAdminUserIdEqualTo(adminUserId).andIsDeleteEqualTo(PlaceConstants.NO);
        List<TbSupplierUser> tbSupplierUserList = tbSupplierUserMapper.selectByExample(tbSupplierUserExample);
        if (tbSupplierUserList.isEmpty()){
            return APIResponse.returnFail("没有关联供应商！");
        }
        List<Integer> supplierIds = new ArrayList<>();
        for (TbSupplierUser tbSupplierUser : tbSupplierUserList){
            supplierIds.add(tbSupplierUser.getSupplierId());
        }
        if (supplierIds.isEmpty()){
            return APIResponse.returnFail("没有关联供应商！");
        }
        TbSupplierExample tbSupplierExample = new TbSupplierExample();
        tbSupplierExample.createCriteria().andIdIn(supplierIds).andIsDeleteEqualTo(PlaceConstants.NO);
        List<TbSupplier> supplierList = supplierMapper.selectByExample(tbSupplierExample);
        return APIResponse.returnSuccess(supplierList);
    }

    /**
     * 查询供应商所属场馆
     * @param supplierId
     * @return
     */
    @Override
    public List<TbBizPlace> getPlaceListForSupplier(Integer supplierId) {
        if (null == supplierId){
            return null;
        }
        TbBizPlaceExample tbPlaceExample = new TbBizPlaceExample();
        tbPlaceExample.createCriteria().andSupplierIdEqualTo(supplierId);
        List<TbBizPlace> placeList = tbBizPlaceMapper.selectByExample(tbPlaceExample);
        return placeList;
    }
}
